package com.itheima.controller;

import com.itheima.common.JsonResult;
import com.itheima.common.SnowFlake;
import com.itheima.pojo.admin.Category;
import com.itheima.pojo.admin.Pagination;
import com.itheima.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.util.List;

/**
 * @author ChenJunJie
 * @date 2022/6/13 16:22
 * 分类controller层
 */
@RestController
@RequestMapping(value = "/category", produces = "application/json;charset=utf-8")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;
    @Autowired
    private SnowFlake snowFlake;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    //新增分类
    @PostMapping
    public JsonResult<String> categoryAdd(@RequestBody Category category, HttpServletRequest request) {

        long id = snowFlake.nextId();
        category.setId(id + "");

        String token = request.getHeader("Authorization");
        String username = redisTemplate.opsForValue().get(token);

        category.setCreateUser(username);

        return categoryService.categoryAdd(category);
    }

    //按照分页查询分类
    @GetMapping("/page")
    public JsonResult<Pagination<Category>> categoryPagination(@RequestParam("page") Integer pageNum, Integer pageSize) throws ParseException {

        return categoryService.categoryPagination(pageNum, pageSize);

    }

    //通过分类ID删除分类
    @DeleteMapping
    public JsonResult<String> categoryDeleteById(@RequestParam("id") String id){

        return categoryService.categoryDeleteById(id);
    }

    //通过分类id修改分类
    @PutMapping
    public JsonResult<String> categoryUpdateById(@RequestBody Category category,HttpServletRequest request){

        String token = request.getHeader("Authorization");
        String username = redisTemplate.opsForValue().get(token);

        category.setUpdateUser(username);

        boolean b = categoryService.categoryUpdateById(category);

        if (b){
            return JsonResult.success("修改成功");
        }else {
            return JsonResult.error("修改成功");
        }
    }

    //通过分类类型查询分类
    @GetMapping("/list")
    public JsonResult< List<Category>> categorySelectByType(@RequestParam("type") Integer type){
        List<Category> categories = categoryService.categorySelectByType(type);

        if (categories.size()>0){
            return JsonResult.select(categories, "查询成功");
        }else {
            return JsonResult.error("查询失败");
        }
    }
}
